package cn.fenqing168.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author fenqing
 */
@RestController
@Slf4j
public class TestController {

    @GetMapping("/test1")
    public String test1() throws InterruptedException {
        // 模拟线程需要5秒钟才能处理完，使得当前线程没处理完时后续的请求直接触发流控处理
        TimeUnit.SECONDS.sleep(5);
        return "test1";
    }

    @GetMapping("/test2")
    public String test2(){
        log.info("{}线程，\ttest2", Thread.currentThread().getName());
        return "test2";
    }

    @SneakyThrows
    @GetMapping("/test3")
    public String test3(){
        TimeUnit.SECONDS.sleep(1);
        log.info("{}线程，处理test3", Thread.currentThread().getName());
        return "test3";
    }

    /**
     * 测试熔断的异常比例
     * @return 响应结果
     */
    @GetMapping("/test4")
    public String test4(){
        // 模拟报错的比例
        int num = new Random().nextInt(100);
        // 20%几率报错
        if(num < 20){
            throw new RuntimeException("模拟报错");
        }
        return "test4";
    }

    @GetMapping("/test5")
    public String test5(){
        int age = 1 / 0;
        return "test5";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "blockHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,@RequestParam(value = "p2", required = false) String p2){
        return "成功！p1:" + p1 + ",p2:" + p2;
    }

    public String blockHotKey(String p1, String p2, BlockException e){
        return "被限流，触发降级，p1: " + p1 + ", p2:" + p2 + ", 异常信息为：" + e.getMessage();
    }

}
